﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Text.RegularExpressions;

namespace JustPlus
{
    /// <summary>
    /// GenePanel.xaml 的交互逻辑
    /// </summary>
    public partial class GenePanel : UserControl
    {
        public int page = 0;//当前页，每页4个GeneBox
        private int panelpage = 0;
        private int cate;//0:最多收藏；1:最近生成；2:私人基因
        public static string context = "";//Uri
        public Muggy muggy;
        private List<GeneInfo> geneinfo;
        private int failcount = 0;//载入错误的次数
        private string radioID1 = "";
        private string radioID2 = "";
        public GenePanel()
        {
            InitializeComponent();
            image1.Opacity = 0.7;
            image2.Opacity = 0;
            image3.Opacity = 0;
            //
            label3.Opacity = 0;
            //
            muggy = new Muggy();
            geneinfo = new List<GeneInfo>();
            LoadGeneBox();
        }

        //收藏最多
        private void label1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            image1.Opacity = 0.7;
            image2.Opacity = 0;
            image3.Opacity = 0;

            cate = 0;
            page = 0;//初始化页码
            panelpage = 0;
            muggy.MuggyList.Clear();
            LoadGeneBox();
        }


        //最近生成
        private void label2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            image1.Opacity = 0;
            image2.Opacity = 0.7;
            image3.Opacity = 0;

            cate = 1;
            page = 0;//初始化页码,每页4个
            panelpage = 0;//每页2个
            muggy.MuggyList.Clear();
            LoadGeneBox();
        }

        //私人基因
        private void label3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
          /*  image1.Opacity = 0;
            image2.Opacity = 0;
            image3.Opacity = 0.7;

            cate = 2;
            page = 0;//初始化页码
            panelpage = 0;
            muggy.MuggyList.Clear();
            LoadGeneBox();
          */
        }

        //载入公共音乐基因
        private void LoadGeneBox()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
            {
                if ((panelpage + 1) * 2 > page * 4)
                {
                    //page = page + 1;
                    Parameters parameters = new Parameters();
                    parameters.Add("s", (page * 4).ToString());
                    //parameters.Add("ck", "w6qr");
                    parameters.Add("ck", "null");
                    string GeneJson = "";
                    if (cate == 0)
                        GeneJson = new ConnectionBase().Post("http://labs.douban.com/j/muggy/j_popular_gene", Encoding.UTF8.GetBytes(parameters.ToString()));
                    else if (cate == 1)
                        GeneJson = new ConnectionBase().Post("http://labs.douban.com/j/muggy/j_recent_gene", Encoding.UTF8.GetBytes(parameters.ToString()));
                    else if(cate == 2)
                        GeneJson = new ConnectionBase().Get("http://labs.douban.com/muggy/mine");
                    if (GeneJson == null)
                    {
                        failcount = failcount + 1;
                        if (failcount <= 3)
                            LoadGeneBox();
                        else
                        {
                            failcount = 0;
                            Dispatcher.Invoke(new Action(() =>
                            {
                                label5.Opacity = 1.0;
                                label5.Content = @"加载失败，请检查网络或者点击重试！";
                            }));
                        }
                        return;
                    }
                    //int tmpcount = muggy.MuggyList.Count;
                    if(cate == 0||cate == 1)
                        muggy.AddNewMuggy(GeneJson);
                    else if(cate == 2)
                        muggy.AddPrivateMuggy(GeneJson);

                    geneinfo = muggy.MuggyList;
                    page = page + 1;
                    if (geneinfo.Count <= panelpage * 2 + 1)
                    {
                        failcount = failcount + 1;
                        if (failcount <= 3)
                            LoadGeneBox();
                        else
                        {
                            failcount = 0;
                            Dispatcher.Invoke(new Action(() =>
                            {
                                label5.Opacity = 1.0;
                                label5.Content = @"加载失败，请检查网络或者点击重试！";
                            }));
                        }
                        return;
                    }
                }

                radioID1 = geneinfo[panelpage * 2].RadioID;
                radioID2 = geneinfo[panelpage * 2 + 1].RadioID;

                Dispatcher.Invoke(new Action(() =>
                {
                    label5.Opacity = 0;
                    defGeneBox1.image1.Source = new BitmapImage(new Uri(Uri.UnescapeDataString(geneinfo[panelpage * 2].Photo), UriKind.Absolute));
                    defGeneBox1.button1.Content = geneinfo[panelpage * 2].NickName;
                    defGeneBox1.label2.Content = geneinfo[panelpage * 2].SingerName[0];
                    defGeneBox1.label3.Content = geneinfo[panelpage * 2].SingerName[1];
                    defGeneBox1.label4.Content = geneinfo[panelpage * 2].SingerName[2];
                    defGeneBox1.label5.Content = geneinfo[panelpage * 2].SingerName[3];
                    defGeneBox1.label6.Content = geneinfo[panelpage * 2].SingerName[4];
                    defGeneBox1.label7.Content = geneinfo[panelpage * 2].SingerName[5];
                    defGeneBox1.label8.Content = geneinfo[panelpage * 2].SingerName[6];

                    defGeneBox2.image1.Source = new BitmapImage(new Uri(Uri.UnescapeDataString(geneinfo[panelpage * 2 + 1].Photo), UriKind.Absolute));
                    defGeneBox2.button1.Content = geneinfo[panelpage * 2 + 1].NickName;
                    defGeneBox2.label2.Content = geneinfo[panelpage * 2 + 1].SingerName[0];
                    defGeneBox2.label3.Content = geneinfo[panelpage * 2 + 1].SingerName[1];
                    defGeneBox2.label4.Content = geneinfo[panelpage * 2 + 1].SingerName[2];
                    defGeneBox2.label5.Content = geneinfo[panelpage * 2 + 1].SingerName[3];
                    defGeneBox2.label6.Content = geneinfo[panelpage * 2 + 1].SingerName[4];
                    defGeneBox2.label7.Content = geneinfo[panelpage * 2 + 1].SingerName[5];
                    defGeneBox2.label8.Content = geneinfo[panelpage * 2 + 1].SingerName[6];
                }));
                defGeneBox1.ButtonClicked+=new SubModel.DefGeneBox.ButtonClickedEventHandler(Button1_Clicked);
                defGeneBox2.ButtonClicked += new SubModel.DefGeneBox.ButtonClickedEventHandler(Button2_Clicked);
            }));
        }

        //载入私人音乐基因频道
        private void LoadPrivateGeneBox()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
                {
                    string generesult = new ConnectionBase().Get(@"http://labs.douban.com/muggy/mine");
                    if (string.IsNullOrEmpty(generesult))
                    {
                        Dispatcher.Invoke(new Action(() =>
                        {
                            label5.Opacity = 1.0;
                            label5.Content = @"加载失败，请检查网络或者点击重试！";
                        }));
                    }
                    else
                    {
                        Match match = Regex.Match(generesult, @"<li id=.*?class=""gene-card"">(\s+.*)+?\s+</ol>", RegexOptions.IgnoreCase);
                        if (match.Groups.Count <= 1)
                        {
                            Dispatcher.Invoke(new Action(() =>
                            {
                                label5.Opacity = 1.0;
                                label5.Content = @"您还没有检测基因，也没有收藏别人的哦，还不快去！";
                            }));
                        }
                        else
                        {
                            for (int i = 0; i < match.Groups.Count - 2; i++ )
                            {
                                string s=match.Groups[i].Value;
                                Match gidmatch = Regex.Match(s, @"id=\""gid\"" value=\""([^\""]+)\""");
                                geneinfo[i].GeneID = gidmatch.Groups[0].Value;
                                Match usernamematch = Regex.Match(s, @"alt=\""([^\""]+)\""");
                                geneinfo[i].NickName = usernamematch.Groups[0].Value;
                                Match photomatch = Regex.Match(s, @"src=\""([^\""]+)\""");
                                geneinfo[i].Photo = photomatch.Groups[0].Value;
                                Match useridmatch = Regex.Match(s, @"<a class=\""user-info-name\"" href=\""/muggy/([^\""]+)\"">");
                                geneinfo[i].UserID = useridmatch.Groups[0].Value;
                                Match singermatch = Regex.Match(s, @"<a class=\""user-info-name\"" href=\""/muggy/([^\""]+)\"">");
                                for (int j = 0; j < 7; j++)
                                {
                                    geneinfo[i].SingerName.Add(singermatch.Groups[i].Value);
                                }
                                Match radioidmatch = Regex.Match(s, @"<a href=\""http://douban.fm/?context=channel:0|muggy:([^\""]+)\"" target=\""_blank\""></a>");
                                geneinfo[i].UserID = radioidmatch.Groups[0].Value;
                            }
                        }
                    }
                }));
        }


        //离开当前界面
        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel3);
        }

        private void image5_MouseEnter(object sender, MouseEventArgs e)
        {
            image5.Opacity = 1.0;
        }

        private void image5_MouseLeave(object sender, MouseEventArgs e)
        {
            image5.Opacity = 0.6;
        }

        private void image4_MouseEnter(object sender, MouseEventArgs e)
        {
            image4.Opacity = 1.0;
        }

        private void image4_MouseLeave(object sender, MouseEventArgs e)
        {
            image4.Opacity = 0.6;
        }

        //panelpage下一页
        private void image5_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (muggy.MuggyList.Count < (panelpage + 1) * 2)
                return;
            panelpage = panelpage + 1;
            if (panelpage == 2)
                image4.Opacity = 0.6;
            LoadGeneBox();
        }

        //panelpage上一页
        private void image4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            panelpage = panelpage - 1;
            if (panelpage < 0)
            {
                panelpage = panelpage + 1;
                image4.Opacity = 0;
                return;
            }

            LoadGeneBox();
        }

        //收听
        private void defGeneBox1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            GetSongList.currentchannel = new Channel(2, 0, @"私人基因");
            context = @"channel:0|muggy:" + radioID1;

            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);

            PlayerPanel playerpanel = (PlayerPanel)mwnd.stackPanel3.Children[0];
            playerpanel.getsong.Next(true);
        }

        private void defGeneBox2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            GetSongList.currentchannel = new Channel(2, 0, @"私人基因");
            context = @"channel:0|muggy:" + radioID2;

            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);

            PlayerPanel playerpanel = (PlayerPanel)mwnd.stackPanel3.Children[0];
            playerpanel.getsong.Next(true);
        }

        private void Button1_Clicked(object sender)
        {
            GetSongList.currentchannel = new Channel(2, 0, @"私人基因");
            context = @"channel:0|muggy:" + radioID1;

            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);

            PlayerPanel playerpanel = (PlayerPanel)mwnd.stackPanel3.Children[0];
            playerpanel.getsong.Next(true);
        }

        private void Button2_Clicked(object sender)
        {
            GetSongList.currentchannel = new Channel(2, 0, @"私人基因");
            context = @"channel:0|muggy:" + radioID2;

            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);

            PlayerPanel playerpanel = (PlayerPanel)mwnd.stackPanel3.Children[0];
            playerpanel.getsong.Next(true);
        }
    }
}
